#include "Task.h"
#include "EchoServer.h"
#include <iostream>
#include <sstream>

using std::cout;
using std::endl;

TimerTask::TimerTask(EchoServer* server) 
: _server(server)
, _startTime(std::chrono::steady_clock::now())
{
}

void TimerTask::registerHeartbeat()
{
    // 每30秒发送一次心跳信息
    _server->runEvery(std::chrono::milliseconds(30000), [this]() {
        auto now = std::chrono::steady_clock::now();
        auto uptime = std::chrono::duration_cast<std::chrono::seconds>(now - _startTime);
        cout << "[Heartbeat] 服务器运行时间: " << uptime.count() << "秒" << endl;
    });
    cout << "[Task] 心跳检测任务已注册" << endl;
}

void TimerTask::registerStatusReport()
{
    // 每60秒报告服务器状态
    _server->runEvery(std::chrono::milliseconds(60000), [this]() {
        cout << "[Status] ====== 服务器状态报告 ======" << endl;
        cout << "[Status] 运行时间: " << 
            std::chrono::duration_cast<std::chrono::seconds>(
                std::chrono::steady_clock::now() - _startTime).count() << "秒" << endl;
        cout << "[Status] 当前连接数: " << _connectionCount << endl;
        cout << "[Status] ===========================" << endl;
    });
    cout << "[Task] 状态报告任务已注册" << endl;
}

void TimerTask::registerConnectionTimeout()
{
    // 每5分钟检查一次连接超时
    _server->runEvery(std::chrono::milliseconds(300000), [this]() {
        cout << "[Task] 执行连接超时检查..." << endl;
        // 这里可以添加具体的超时检查逻辑
    });
    cout << "[Task] 连接超时检测任务已注册" << endl;
}

void TimerTask::registerWelcomeMessage()
{
    // 服务器启动5秒后发送欢迎消息
    _server->runAfter(std::chrono::milliseconds(5000), []() {
        cout << "[Welcome] ====================================" << endl;
        cout << "[Welcome] 🎉 Echo服务器启动完成！" << endl;
        cout << "[Welcome] 📡 监听端口: 8888" << endl;
        cout << "[Welcome] ⚡ 支持定时任务功能" << endl;
        cout << "[Welcome] 🔗 等待客户端连接..." << endl;
        cout << "[Welcome] ====================================" << endl;
    });
    cout << "[Task] 欢迎消息任务已注册" << endl;
}

void TimerTask::registerCleanupTask()
{
    // 每小时执行一次清理任务
    _server->runEvery(std::chrono::milliseconds(3600000), [this]() {
        cout << "[Cleanup] 执行定期清理任务..." << endl;
        // 这里可以添加日志清理、内存整理等逻辑
        cout << "[Cleanup] 清理任务完成" << endl;
    });
    cout << "[Task] 清理任务已注册" << endl;
}

int64_t TimerTask::scheduleDelayedMessage(const std::string& message, std::chrono::milliseconds delay)
{
    return _server->runAfter(delay, [message]() {
        cout << "[DelayedMsg] " << message << endl;
    });
}

int64_t TimerTask::schedulePeriodicTask(const std::string& taskName, std::chrono::milliseconds interval, 
                                  TimerCallback&& callback)
{
    cout << "[Task] 注册周期任务: " << taskName 
         << ", 间隔: " << interval.count() << "ms" << endl;
    return _server->runEvery(interval, std::move(callback));
}

void TimerTask::cancelTask(int64_t timerId)
{
    _server->cancelTimer(timerId);
    cout << "[Task] 取消任务 ID: " << timerId << endl;
}